/*
Copyright 2009 - 2013 Peter Krajnc, SCREENWORKER

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.compactmvc.services.jsservice
{
	import flash.external.ExternalInterface;
	
	import org.compactmvc.interfaces.IModel;
	import org.compactmvc.patterns.Controller;
	import org.compactmvc.patterns.Model;
	import org.compactmvc.services.interfaces.IJSService;

	public class JSService extends Model implements IModel, IJSService
	{
		public static const availabilityExtInt:Boolean 	= ExternalInterface.available;	
		
		private var _jsCallbackList:Array = [];
		
		public function JSService(name:String, controller:Controller)
		{
			super(name, controller);
		}
		
		public function errorHandler(message:String):void
		{
			//overriden by subclass
		}
		
		 /**
	     * adds a Javascript Callback Listener 
	     * 
	     */		
	    protected function addJavascriptListener(jsFunctionName:String, closureMethod:Function):void
	    {
		   	 if (availabilityExtInt) 
		   	 {	 
		   	 	ExternalInterface.addCallback(jsFunctionName, closureMethod);		   	 	
			 }
			 else
			 {
			 	errorHandler('ExternalInterface not available!');
			 }
		}
		
		/**
	     * calls a Javascript Method
	     * 
	     */		
	    protected function callJavascriptMethod(functionName:String, ...parameters):void
	    {
		   	 if (availabilityExtInt) 
		   	 {	 
		   	 	ExternalInterface.call( functionName, parameters)	 	
			 }
			 else
			 {
			 	errorHandler('ExternalInterface not available!');
			 }
		}
		
		/**
		 * checks if a js method exists or not 
		 * @param methodName
		 * @return 
		 * 
		 */		
		protected function existMethod(methodName:String):Boolean
		{
			if (availabilityExtInt)
			{
				// check if function is avialable 
				if( ExternalInterface.call('function() { return (typeof ' + methodName + ' != "undefined"); }') as Boolean)
					return true;
			}
			return false;
		}
		
	}
}
